package com.czk.durant.springframework.beans.factory.support;

import com.czk.durant.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;

/**
 * jdk的实例化
 *
 * @Author:ChenZhangKun
 * @Date: 2021/6/9 15:27
 */
public class SimpleInstantiationStrategy implements InstantiationStrategy {
    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor constructor, Object[] args) {
        // 拿到class
        Class clazz = beanDefinition.getBeanClass();
        Object object = null;
        //
        try {
            if (constructor != null) {
                // 拿到参数类型
                Class[] parameterTypes = constructor.getParameterTypes();
                // 实例化
                // 这里按理说还应该比对参数类型
                object = clazz.getDeclaredConstructor(parameterTypes).newInstance(args);
                return object;
            } else {
                return clazz.getDeclaredConstructor().newInstance();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException("初始化异常");
        }
    }
}
